/**
 * Pangolin IM Server
 * autor:   yiyefangzhou24
 * email:   yiyefangzhou24@qq.com
 * data:    21/10/1
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include "package.h"

void package_head_new(int command,char *out){
    //封装包头
    PACKAGE_HEAD *pkgHead;
    pkgHead = (PACKAGE_HEAD *)malloc(sizeof(PACKAGE_HEAD));

    pkgHead->package_len = htonl(PACKAGE_HEAD_LEN);
    pkgHead->head_len = htons(PACKAGE_HEAD_LEN);
    pkgHead->version = htons(PACKAGE_VERSION);
    pkgHead->command = htonl(command);
    pkgHead->idx = htonl(1);
    memcpy(out,pkgHead,PACKAGE_HEAD_LEN);
    free(pkgHead);
}

void package_new(char *context,int len,int idx,int command, char *out){

    //封装包头
    PACKAGE_HEAD *pkgHead;
    pkgHead = (PACKAGE_HEAD *)malloc(sizeof(PACKAGE_HEAD));
    int pkg_len = len + PACKAGE_HEAD_LEN;
    pkgHead->package_len = htonl(pkg_len);
    pkgHead->head_len = htons(PACKAGE_HEAD_LEN);
    pkgHead->version = htons(PACKAGE_VERSION);
    pkgHead->command = htonl(command);
    pkgHead->idx = htonl(idx);

    memcpy(out,pkgHead,PACKAGE_HEAD_LEN);
    memcpy(out + PACKAGE_HEAD_LEN,context,len);
    free(pkgHead);
}

void get_package_head(PACKAGE_HEAD * head,char * data){
    PACKAGE_HEAD tmp;
    memcpy(&tmp , data , PACKAGE_HEAD_LEN);
    head->package_len = ntohl(tmp.package_len);
    head->head_len = ntohs(tmp.head_len);
    head->version = ntohs(tmp.version);
    head->command = ntohl(tmp.command);
    head->idx = ntohl(tmp.idx);
}